from django.shortcuts import render, redirect, reverse
from django.http.response import JsonResponse
import string
import random
from django.core.mail import send_mail
from .models import CaptchaModel
from django.views.decorators.http import require_http_methods
from .forms import RegisterForm, LoginForm
from django.contrib.auth import get_user_model, login, logout

User = get_user_model()

# Create your views here.
@require_http_methods(["GET", "POST"])
def pylogin(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            # 处理登录逻辑
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            user = User.objects.filter(email=email).first()
            if user and user.check_password(password):
                # 登录成功
                login(request, user)

                if not remember:
                    # 设置过期时间为0，浏览器关闭后失效
                    request.session.set_expiry(0)
                # 如果点击了，就使用默认的两周过期时间
                return redirect('/')
            else:
                print('邮箱或密码错误！')
                # form.add_error('email', "邮箱或密码错误！")
                # return render(request, 'login.html', context={'form': form})
                return redirect(reverse('pyauth:login'))


@require_http_methods(["GET", "POST"])
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            # 处理注册逻辑
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            User.objects.create_user(username=username, email=email, password=password)
            return redirect(reverse('pyauth:login'))
        else:
            print(form.errors)
            # 重新跳转到注册页面
            return redirect(reverse('pyauth:register'))

def send_email_captcha(request):
    email = request.GET.get('email')
    if not email:
        return JsonResponse({"code":400, "msg":"必须传递邮箱！"})
    # 生成验证码（随机的四位阿拉伯数字）
    captcha = "".join(random.sample(string.digits, 4))
    # 存储到数据库中
    CaptchaModel.objects.update_or_create(
        email=email,
        defaults={'captcha': captcha}
    )
    send_mail("PyBlog注册验证码", message=f"您的验证码是：{captcha}", recipient_list=[email], from_email=None)
    return JsonResponse({"code":200, "msg":"验证码发送成功！", "captcha":captcha})

def pylogout(request):
    logout(request)
    return redirect('/')